package com.dg.cuckoo.admin.service.impl;

import com.dg.cuckoo.admin.dto.basicInformation.constructionUnit.ConstructionUnitDto;
import com.dg.cuckoo.admin.dto.basicInformation.permissionSettings.UnitTypeDto;
import com.dg.cuckoo.admin.repository.ConstructionRepository;
import com.dg.cuckoo.admin.repository.UnitTypeRepository;
import com.dg.cuckoo.admin.service.ConstructionService;
import com.dg.cuckoo.core.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ConstructionServiceimpl implements ConstructionService {

    @Autowired
    private ConstructionRepository repository;
    @Autowired
    private UnitTypeRepository unitTypeRepository;//建设单位jpa

    @Override
    public void save(ConstructionUnitDto dto) {
        dto=checkSave(dto);//字段校验
        repository.save(dto);
    }

    @Override
    public ConstructionUnitDto openInfo(String id) {
        ConstructionUnitDto dto = repository.findById(id).get();
        return dto;
    }

    @Override
    public void update(ConstructionUnitDto dto,String id) {
        if(id==null){
            throw new ServiceException("请选择建设单位");
        }
        dto.setId(id);
        repository.save(dto);
    }

    @Override
    public void delect(String id) {
        if(id==null){
            throw new ServiceException("请选择建设单位");
        }
        repository.deleteById(id);
    }

    @Override
    public List<String> openDropDown() {
        List<UnitTypeDto> units = unitTypeRepository.findAll();
        List<String> data=new ArrayList<>();
        for(UnitTypeDto u:units){
            data.add(u.getTypeName());
        }
        return data;
    }


    private ConstructionUnitDto checkSave(ConstructionUnitDto dto){
        if(dto.getConstructionName()==null){
            throw new ServiceException("建设单位名称不能为空");
        }
        if(repository.findByConstructionName(dto.getConstructionName())!=null){
            throw new ServiceException("建设单位名称已存在，请更换");
        }
        if(dto.getConstructionNumber()==null){
            throw new ServiceException("建设单位编号不能为空");
        }
        if(repository.findByConstructionNumber(dto.getConstructionNumber())!=null){
            throw new ServiceException("建设单位编号已存在，请更换");
        }
        if(dto.getUnitType()==null){
            dto.setUnitType("");
        }
        return dto;
    }

    @Override
    public List<String> byUnitType(String unitType){ //通过单位类型获取里面的字符串
        List<ConstructionUnitDto> dtos = repository.findByUnitType(unitType);
        List<String> list=new ArrayList<>();
        for (ConstructionUnitDto c:dtos){
            list.add(c.getConstructionName());
        }
        return list;
    }
}
